package com.superjson.showpro.service.impl;

import com.superjson.showpro.base.GenericServiceImpl;
import com.superjson.showpro.dao.ArticleCatalogUserDao;
import com.superjson.showpro.entity.ArticleCatalog;
import com.superjson.showpro.entity.ArticleCatalogUser;
import com.superjson.showpro.entity.User;
import com.superjson.showpro.service.ArticleCatalogService;
import com.superjson.showpro.service.ArticleCatalogUserService;
import com.superjson.showpro.service.UserService;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultCodeEnum;
import com.superjson.showpro.shared.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import static java.util.Objects.isNull;

@Service
public class ArticleCatalogUserServiceImpl extends GenericServiceImpl<ArticleCatalogUser> implements ArticleCatalogUserService {

    private ArticleCatalogUserDao articleCatalogUserDao;

    @Autowired
    private ArticleCatalogService articleCatalogService;
    @Autowired
    private UserService userService;

    @Autowired
    public ArticleCatalogUserServiceImpl(ArticleCatalogUserDao articleCatalogUserDao) {
        super(articleCatalogUserDao);
        this.articleCatalogUserDao = articleCatalogUserDao;
    }

    @Override
    public Result saveObj(Long articleId, User user, HttpServletRequest request) {
        if (isNull(articleId) || articleId < 0) {
            return ResultUtil.buildFailed(ResultCodeEnum.NO_ARTICLE);
        }
        ArticleCatalog articleCatalog = articleCatalogService.get(articleId).getResultData();
        if (isNull(articleId) || articleId < 0) {
            return ResultUtil.buildFailed(ResultCodeEnum.NO_ARTICLE);
        }
        ArticleCatalogUser acu = new ArticleCatalogUser();
        acu.setArticleCatalog(articleCatalog);
        acu.setUser(isNull(user) ? null : userService.get(user.getId()).getResultData());
        articleCatalogUserDao.save(acu);
        return ResultUtil.buildSuccess();
    }

    @Override
    public Result<Long> countClick(Long articleId, Long userId) {
        return ResultUtil.buildSuccess(articleCatalogUserDao.countClick(articleId,userId));
    }
}